﻿using Commands;
using ShapeManager;
using UserControls;
using System.Drawing;
using System.Windows.Forms;
using System;

namespace Tools
{
    /// <summary> 选中模式枚举 </summary>
    public enum SelectionMode
    {
        /// <summary> None </summary>
        None,
        /// <summary> 网格选中 </summary>
        NetSelection,
        /// <summary> 移动 </summary>
        Move,
        /// <summary> 调整大小 </summary>
        Size,
        /// <summary> 旋转 </summary>
        Rotate,
    }
    public class ToolPointer : ToolObject
    {
        /// <summary> 选择模式 </summary>
        private SelectionMode selectMode = SelectionMode.None;
        /// <summary> 当前正在调整大小的对象 </summary>
        private DrawObject resizedObject;
        private DrawObject rotateObject;
        /// <summary> 调整大小手柄  </summary>
        private int resizedObjectHandle;
        private int rotateObjectHandle;
        /// <summary> 保存当前位置的状态（用于移动和调整对象） </summary>
        private PointF startPoint = new PointF(0, 0);
        /// <summary> 保存最后位置的状态（用于移动和调整对象） </summary>
        private PointF lastPoint = new PointF(0, 0);
        /// <summary> 状态变更命令 </summary>
        private CommandChangeState commandChangeState;
        /// <summary> 移动 </summary>
        private bool wasMove;

        public ToolPointer() { }
        /// <summary> 鼠标按下 </summary>
        public override void OnMouseDown(UImageWindow uImageWindow, MouseEventArgs e)
        {
            commandChangeState = null;
            wasMove = false;
            selectMode = SelectionMode.None;
            PointF point = new PointF(e.X, e.Y);
            // 测试调整大小(只有选中控件时,光标就在手柄上)
            foreach (DrawObject obj in uImageWindow.ShapeList.Selection)
            {
                int handleNumber = obj.HitTest(point);
                if (handleNumber > 0)
                {
                    if(handleNumber == 9 && obj.IsRotating)
                    {
                        selectMode = SelectionMode.Rotate;
                        rotateObject = obj;
                        rotateObjectHandle = handleNumber;
                        uImageWindow.ShapeList.UnselectAll();
                        obj.IsSelected = true;
                        commandChangeState = new CommandChangeState(uImageWindow.ShapeList);
                        break;
                    }
                    else
                    {
                        selectMode = SelectionMode.Size;
                        resizedObject = obj;
                        resizedObjectHandle = handleNumber;
                        uImageWindow.ShapeList.UnselectAll();
                        obj.IsSelected = true;
                        commandChangeState = new CommandChangeState(uImageWindow.ShapeList);
                        break;
                    }
                }
            }
            // 移动测试（光标位于对象上）
            if (selectMode == SelectionMode.None)
            {
                int count = uImageWindow.ShapeList.Count;
                DrawObject obj = null;
                for (int i = 0; i < count; i++)
                {
                    if (uImageWindow.ShapeList[i].HitTest(point) == 0)
                    {
                        obj = uImageWindow.ShapeList[i];
                        break;
                    }
                }
                if (obj != null)
                {
                    selectMode = SelectionMode.Move;
                    // 如果没有按下Ctrl 且点击对象不是选中状态，则取消选中状态。
                    if ((Control.ModifierKeys & Keys.Control) == 0 && !obj.IsSelected)
                        uImageWindow.ShapeList.UnselectAll();
                    // 选择点击对象
                    obj.IsSelected = true;
                    commandChangeState = new CommandChangeState(uImageWindow.ShapeList);
                    uImageWindow.Cursor = Cursors.SizeAll;
                }
            }
            // 网格选择
            if (selectMode == SelectionMode.None)
            {
                // 点击背景
                if ((Control.ModifierKeys & Keys.Control) == 0)
                    uImageWindow.ShapeList.UnselectAll();
                selectMode = SelectionMode.NetSelection;
            }
            lastPoint.X = e.X;
            lastPoint.Y = e.Y;
            startPoint.X = e.X;
            startPoint.Y = e.Y;
            uImageWindow.Capture = true;
            uImageWindow.Refresh();
            if (selectMode == SelectionMode.NetSelection)
            {
                // 在初始位置绘制选择矩形
                Rectangle rect = Rectangle.Round(URectangle.GetNormalizedRectangle(startPoint, lastPoint));
                Rectangle screenRect = uImageWindow.RectangleToScreen(rect);
                Console.WriteLine($"Control rect: {rect}, Screen rect: {screenRect}");
                ControlPaint.DrawReversibleFrame(screenRect, Color.Black, FrameStyle.Dashed);
            }
        }
        /// <summary>  鼠标移动 </summary>
        public override void OnMouseMove(UImageWindow uImageWindow, MouseEventArgs e)
        {
            PointF point = new PointF(e.X, e.Y);
            PointF oldPoint = lastPoint;
            wasMove = true;
            // 当鼠标按钮没按下时 设置光标 
            if (e.Button == MouseButtons.None)
            {
                Cursor cursor = null;
                for (int i = 0; i < uImageWindow.ShapeList.Count; i++)
                {
                    int n = uImageWindow.ShapeList[i].HitTest(point);
                    if (n > 0)
                    {
                        cursor = uImageWindow.ShapeList[i].GetHandleCursor(n);
                        break;
                    }
                }
                if (cursor == null)
                    cursor = Cursors.Default;
                uImageWindow.Cursor = cursor;
                return;
            }
            if (e.Button != MouseButtons.Left) return;
            if (selectMode == SelectionMode.Rotate)
            {
                if (rotateObject != null)
                {
                    rotateObject.Rotate(point, lastPoint);
                    uImageWindow.SetDirty();
                    uImageWindow.Refresh();
                }
            }
            //找出上一个点位和当前点位之间的差异。  
            float dx = e.X - lastPoint.X;
            float dy = e.Y - lastPoint.Y;
            lastPoint.X = e.X;
            lastPoint.Y = e.Y;
            // 调整大小
            if (selectMode == SelectionMode.Size)
            {
                if (resizedObject != null)
                {
                    resizedObject.MoveHandleTo(point, resizedObjectHandle);
                    uImageWindow.SetDirty();
                    uImageWindow.Refresh();
                }
            }
            // 移动
            if (selectMode == SelectionMode.Move)
            {
                foreach (DrawObject obj in uImageWindow.ShapeList.Selection)
                {
                    obj.Move(dx, dy);
                }
                uImageWindow.Cursor = Cursors.SizeAll;
                uImageWindow.SetDirty();
                uImageWindow.Refresh();
            }
            // 网格选择
            if (selectMode == SelectionMode.NetSelection)
            {
                // 移除旧的矩形
                ControlPaint.DrawReversibleFrame(uImageWindow.RectangleToScreen(Rectangle.Round(
                    URectangle.GetNormalizedRectangle(startPoint, oldPoint))),
                    Color.Black, FrameStyle.Dashed);
                // 绘制新的矩形

                Rectangle rect = Rectangle.Round(URectangle.GetNormalizedRectangle(startPoint, point));
                Rectangle screenRect = uImageWindow.RectangleToScreen(rect);
                Console.WriteLine($"Control rect: {rect}, Screen rect: {screenRect}");
                ControlPaint.DrawReversibleFrame(screenRect, Color.Black, FrameStyle.Dashed);
                uImageWindow.Refresh();
                return;
            }
        }
        /// <summary> 鼠标抬起 </summary>
        public override void OnMouseUp(UImageWindow uImageWindow, MouseEventArgs e)
        {
            if (selectMode == SelectionMode.NetSelection)
            {
                // 移除旧的选中的矩形
                Rectangle rect = Rectangle.Round(URectangle.GetNormalizedRectangle(startPoint, lastPoint));
                Rectangle screenRect = uImageWindow.RectangleToScreen(rect);
                Console.WriteLine($"Control rect: {rect}, Screen rect: {screenRect}");
                ControlPaint.DrawReversibleFrame(screenRect, Color.Black, FrameStyle.Dashed);
                // 进行组选择
                uImageWindow.ShapeList.SelectInRectangle(rect);
                selectMode = SelectionMode.None;
            }
            if (resizedObject != null)
            {
                // 调整大小之后
                resizedObject.Normalize();
                resizedObject = null;
            }
            if (rotateObject != null)
            {
                // 调整大小之后
                rotateObject.Normalize();
                rotateObject = null;
            }
            uImageWindow.Capture = false;
            uImageWindow.Refresh();
            if (commandChangeState != null && wasMove)
            {
                //移动|调整大小之后保存状态 和添加命令到历史。
                commandChangeState.NewState(uImageWindow.ShapeList);
                uImageWindow.AddCommandToHistory(commandChangeState);
                commandChangeState = null;
            }
        }
    }
}
